package com.sc.commons.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sc.commons.gateway.AuthorizationConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * @author
 */
//@Component
public class AuthorizationGlobeFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthorizationConfig authenticationConfig;

    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        ServerHttpResponse serverHttpResponse = exchange.getResponse();

        String url = exchange.getRequest().getURI().getPath();

        // 如果在忽略的列表里,则直接返回
        if (authenticationConfig.getExcludeUrls().contains(url)) {
            return chain.filter(exchange);
        }

        // 获取Token
        String token = serverHttpRequest.getHeaders().getFirst("Authorization");

        // 判断是否有token
        if (!StringUtils.hasText(token)) {
            return authErro(serverHttpResponse, "请登陆");
        }

        // 验证token是否有效
        try{

        } catch (Exception e){

        }


        // 验证是否有权限


//

        return chain.filter(exchange);
    }

    private Mono<Void> authErro(ServerHttpResponse response, String msg) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String returnStr = "";
        try {
            returnStr = objectMapper.writeValueAsString(new HashMap<>() {{
                put("resCode", HttpStatus.UNAUTHORIZED);
                put("resMsg", msg);
            }});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer buffer = response.bufferFactory().wrap(returnStr.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Flux.just(buffer));
    }


    @Override
    public int getOrder() {
        return -1;
    }
}
